package com.ligongmusic.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ligongmusic.R;
import com.ligongmusic.domain.MyPriseDomain;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.util.UniversalAdapter;
import com.ligongmusic.util.ViewHolder;
import com.ligongmusic.view.RoundImageView;
import com.ligongmusic.view.TopManager;
import com.ligongmusic.view.XListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

//http://localhost:8080/music/rankingManage/getAllSongByZan?loginname=13838384384&token=1111&page=0&size=20
public class MyPrise extends Activity implements XListView.IXListViewListener {
	private boolean hasData = true;
	private int page = 0, size = 10;
	private XListView mListView;
	private Handler mHandler = new Handler();
	private List<MyPriseDomain> prises;
	private UniversalAdapter<MyPriseDomain> adapter = null;
	public static DisplayImageOptions options1 = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.head) //设置图片在下载期间显示的图片
			.showImageForEmptyUri(R.drawable.head)//设置图片Uri为空或是错误的时候显示的图片
			.showImageOnFail(R.drawable.head)  //设置图片加载/解码过程中错误时候显示的图片
			.cacheInMemory(true)//设置下载的图片是否缓存在内存中
			.imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
			.bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
			.build();//构建完成;
	public static DisplayImageOptions options2 = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.music_icon) //设置图片在下载期间显示的图片
			.showImageForEmptyUri(R.drawable.music_icon)//设置图片Uri为空或是错误的时候显示的图片
			.showImageOnFail(R.drawable.music_icon)  //设置图片加载/解码过程中错误时候显示的图片
			.cacheInMemory(true)//设置下载的图片是否缓存在内存中
			.imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
			.bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
			.build();//构建完成;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_prise);
        TopManager.getTopManager(this).showTop(true, "我的赞", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
		mListView = (XListView) findViewById(R.id.prise_list);
		mListView.setXListViewListener(this);
		getPriseList();
	}

	private void getPriseList(){
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
		pairs.add(new BasicNameValuePair("token", GlobalParams.token));
		pairs.add(new BasicNameValuePair("page", page + ""));
		pairs.add(new BasicNameValuePair("size", size + ""));
		NetWorkUtils.getRequest(pairs, GlobalParams.MY_PRISE, new NetWorkUtils.NetWorkCallBack() {
			@Override
			public void success(String result) {
				LoggerUtils.getLog(MyPrise.class).error(result);
                onLoad();// 数据刷新成功，调用onLoad方法使上拉或下拉头隐藏
				if (page == 0)// 如果是第一次加载或者是刷新数据，则将原集合数据清空
					prises = new ArrayList<MyPriseDomain>();
				List<MyPriseDomain> temp = JsonUtils.jsonToBeanList(result, MyPriseDomain.class);
				if (temp == null) {
					return;
				}
				hasData = temp.size() == size;// 如果数据有20条，则说明还可以上拉加载
				mListView.setPullLoadEnable(hasData);// 有数据则让ListView可以上拉
				// 将数据保存到适配器集合中
				for (MyPriseDomain p : temp)
                    prises.add(p);
                setAdapter();
			}

			@Override
			public void error() {
			}

			@Override
			public void error(String message) {
				LoggerUtils.getLog(MyPrise.class).error(message);
			}
		});
	}

	public void setAdapter() {
		if (adapter == null) {
			adapter = new UniversalAdapter<MyPriseDomain>(MyPrise.this, prises, R.layout.my_prise_item) {
				@Override
				public void convert(ViewHolder holder, MyPriseDomain t) {
                    ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getPhoto(), (RoundImageView)holder.getView(R.id.user_head), options1);
                    ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getCover(), (ImageView)holder.getView(R.id.music_icon), options2);
                    // 设置字体大小、颜色
					String nick_name = t.getNick_name();
					if (StringUtils.isEmpty(nick_name))
						nick_name = t.getPhone();
					SpannableStringBuilder shareBuilder = new SpannableStringBuilder(nick_name + "上传了单曲");
                    AbsoluteSizeSpan shareSize = new AbsoluteSizeSpan(30);
                    ForegroundColorSpan shareSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_red));
                    shareBuilder.setSpan(shareSpan, 0, nick_name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    shareBuilder.setSpan(shareSize, 0, nick_name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    TextView shareInfo = holder.getView(R.id.tv_share_info);
                    shareInfo.setText(shareBuilder);
                    holder.setText(R.id.tv_upload_date, StringUtils.getYear(t.getUpload_date()));
                    holder.setText(R.id.tv_music_name, t.getSong_name());
                    holder.setText(R.id.tv_singer, t.getMusician_name() + "");

					holder.setText(R.id.tv_prise_num, "赞（" + t.getLike_count() + "）");
				}
			};
			mListView.setAdapter(adapter);
		}else
			adapter.refresh(prises);
	}

	@Override
	public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hasData = true;
                page = 0;
                getPriseList();
            }
        }, 1000);
	}

	@Override
	public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(hasData){
                    page ++;
                    getPriseList();
                }else{
                    onLoad();
                }
            }
        }, 1000);
	}

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(StringUtils.getTime(System.currentTimeMillis()));
    }
}
